﻿using MyX.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LearningEnglish.Models
{
    public class EnglishDictionary : XEntity
    {

        /// <summary>
        /// 从字典中翻译该单词
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public Tuple<string, string> Translate(string word)
        {
            if (string.IsNullOrWhiteSpace(word))
                throw new Exception("单词为空");

            word = word.Trim();
            if (_words.Keys.Contains(word))
                return _words[word];
            if (_words.Keys.Contains(word.ToLower()))
                return _words[word.ToLower()];
            return null;
        }

        public void Add(string word, string mean, string pronunciationFile)
        {
            if (string.IsNullOrWhiteSpace(word))
                throw new Exception("单词为空");
            if (string.IsNullOrWhiteSpace(mean))
                throw new Exception("单词解释为空");
            if (string.IsNullOrWhiteSpace(pronunciationFile))
                throw new Exception("读音文件为空");

            if (_words.Keys.Contains(word))
                throw new Exception("已存在该单词");
            if (_words.Keys.Contains(word.ToLower()))
                throw new Exception("已存在该单词");

            word = word.Trim();
            Update(new EnglishDictionaryWordAdded() { Word = word, Mean = mean });
        }

        public void Do(EnglishDictionaryWordAdded e)
        {
            _words[e.Word] = new Tuple<string, string>(e.Mean, e.PronunciationFile);
        }

        private EnglishDictionary()
            : base()
        {
            _words = new Dictionary<string, Tuple<string, string>>();
        }

        private Dictionary<string, Tuple<string, string>> _words;

        static EnglishDictionary()
        {
            _serviceID = Guid.Parse("0DBC63BE-0DC6-441A-BF41-143A988564B5");
            _instance = new EnglishDictionary();
            _instance.ID = _serviceID;
            _instance.Load();
        }

        private static Guid _serviceID;

        public static EnglishDictionary Instance
        {
            get
            {
                if (_instance == null)
                    throw new Exception("实例化未知错误");
                return _instance;
            }
        }
        private static EnglishDictionary _instance;
    }

    public class EnglishDictionaryWordAdded : XEvent
    {
        public string Word { get; set; }
        public string Mean { get; set; }

        public string PronunciationFile { get; set; }
    }
}